﻿namespace Busconeitor.Web.Controllers
{
    using System.Web.Mvc;
    using System.Web.Security;

    using Busconeitor.Web.Models;
    using Busconeitor.Web.Utils;

    public class AccountController : Controller
    {

        // GET: /Account/LogOn
        public ActionResult LogOn()
        {
            return this.View();
        }

        // POST: /Account/LogOn
        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            if (ModelState.IsValid)
            {
                var user = this.GetUser(model.UserName, model.Password);

                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    Params.CurrentUser = user;

                    return this.RedirectToAction("Index","Home");
                }
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError(string.Empty, Mensajes.UsuarioPasswordIncorrecto);

            return this.View(model);
        }

        // GET: /Account/LogOff
        public ActionResult LogOff()
        {
            Params.CurrentUser = null;
            FormsAuthentication.SignOut();
            Session.Abandon();

            return this.RedirectToAction("Index", "Home");
        }
        
        private LogOnModel GetUser(string userName, string password)
        {
            LogOnModel model = null;

            if (Params.AdminUser.UserName == userName && Params.AdminUser.Password == password)
            {
                model = Params.AdminUser;
            }

            return model;
        }
    }
}
